﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using NetflixFormsApplication.Presentors;
using NetflixMovieService;

namespace NetflixFormsApplication.Views
{
    internal partial class MovieSearchView : Form, IMovieSearchView
    {
        private readonly MovieSearchPresenter _presenter;
        private readonly DataGridView _gridView;

        public MovieSearchView()
        {
            InitializeComponent();

            _presenter = new MovieSearchPresenter(this, new NetflixMovieService.NetflixMovieService());
            _gridView = dataGridView1;
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            IEnumerable<ImageEntity> movieArtCollection = _presenter.RetrieveMovies(releaseYearTextBox.Text, maxResultsTextBox.Text);
            _presenter.UpdateFormDataGridView(movieArtCollection);
        }     

        public void SendMessage(string message)
        {
            resultsTextBox.Text = message;
        }

        public void ClearView()
        {
            if (_gridView != null)
            {
                _gridView.Rows.Clear();
                _gridView.Columns.Clear();
            }

            resultsTextBox.Text = String.Empty;
        }

        public void AddGridRow(DataGridViewRow row)
        {
            if(_gridView.Columns.Count == 0)
                for (int i = 0; i < _presenter.NumberOfGridColumns; i++)
                    _gridView.Columns.Add(new DataGridViewImageColumn());

            _gridView.Rows.Add(row);
        }


        #region Netflix API Methods
        /*
        /// <summary>
        /// NOT USED:  This method uses the OAuth class for communication with the NetFlix API
        /// </summary>
        private void CreateBoxArtGridUsingNetFlixAPI()
        {
            string consumerKey = consumerKeyTextBox.Text.Trim();
            string consumerSecret = sharedSecretTextBox.Text.Trim();

            // Parameter collection
            Collection<Tuple<string, string>> queryParameters = new Collection<Tuple<string, string>>();

            // Search Terms must be set here with URI since it's needed to encode the sig
            string uriString = "http://api.netflix.com/catalog/titles?";
            
            // Add Max results
            int maxResults = 10;
            if (!String.IsNullOrEmpty(maxResultsTextBox.Text) && Int32.TryParse(maxResultsTextBox.Text, out maxResults))
                uriString += "max_results=" + maxResults.ToString();

            // Add title if it exists
            if (!String.IsNullOrEmpty(resultsTextBox.Text))
                uriString += "&term=" + resultsTextBox.Text;
         
            // outputs
            OAuthBase oAuth = new OAuthBase();
            Uri uri = new Uri(uriString);
            
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string normalizedUrl;
            string normalizedRequestParameters;
            string sig = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, string.Empty, string.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
            sig = HttpUtility.UrlEncode(sig);

            StringBuilder sb = new StringBuilder(uri.ToString());
            //sb.AppendFormat("term={0}&", "bob");
            //sb.AppendFormat("max_results={0}&", "10");
            sb.AppendFormat("&oauth_consumer_key={0}&", consumerKey);
            sb.AppendFormat("oauth_nonce={0}&", nonce);
            sb.AppendFormat("oauth_timestamp={0}&", timeStamp);
            sb.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
            sb.AppendFormat("oauth_version={0}&", "1.0");
            sb.AppendFormat("oauth_signature={0}", sig);
            
            // Make the request
            string results = "";
            try
            {
                WebRequest req = WebRequest.Create(sb.ToString());
                WebResponse rsp = req.GetResponse();
                StreamReader sr = new StreamReader(rsp.GetResponseStream());
                results = sr.ReadToEnd();
                rsp.Close();
            }
            catch (Exception ex)
            {
                resultsTextBox.Text = "Request failed: " + ex.Message + " with URL: " + sb;
                return;
            }

            // Set results in text window
            resultsTextBox.Text = sb + "  " + results;
   
        }

        /// <summary>
        /// Generate the timestamp for the signature        
        /// </summary>
        /// <returns>UNIX timestamp</returns>
        public virtual string GenerateTimeStamp()
        {
            // Default implementation of UNIX time of the current UTC time
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        protected Random random = new Random();

        /// <summary>
        /// Generate a nonce
        /// </summary>
        /// <returns>Nonce value</returns>
        public virtual string GenerateNonce()
        {
            // Just a simple implementation of a random number between 123400 and 9999999
            return random.Next(123400, 9999999).ToString();
        }
         * */
        #endregion
    }

    
}
